package com.buynow.cctapi.dao;

import com.buynow.cctapi.util.StringUtils;
import com.buynow.cctapi.util.db.DbBuilder;

import static com.buynow.cctapi.util.StringUtils.GetNewMemberID;

/**
 * Created by jinyunni on 2017-06-05.
 */
public class MemberDao {


    private MemberDao() {
    }

    public static String CreateMemberByMobile(String strMobile) {

        if (!StringUtils.isMobileNumber(strMobile)) {
            return "err:请输入大陆手机号";
        }

        if (hasMemberByMobile(strMobile)) {

            return "err:手机号码已注册";
        }

        return InsetMemberByMobile(strMobile);

    }

    public static String CreateMemberByWx(String strWxID) {

        if (hasMemberByMx(strWxID)) {

            return "err:该会员已存在";
        }
        return GetNewMemberID();
    }

    /**
     * 手机号码是否已注册
     *
     * @param strMobile
     * @return
     */
    public static boolean hasMemberByMobile(String strMobile) {


        String table = StringUtils.GetMobileTableName(strMobile);
        String sql = String.format("select count(*)  from %s where MEMB_MOBILE='%s'", table, strMobile);


        int length = DbBuilder.getCount(sql);

        if (length == 0) {
            return false;
        }
        return true;
    }

    /**
     * 获取会员ID
     *
     * @param strMobile
     * @return
     */
    public static String getMemberByMobile(String strMobile) {


        String table = StringUtils.GetMobileTableName(strMobile);
        String sql = String.format("select count(*) from %s where MEMB_MOBILE='%s'", table, strMobile);


        Object[] result = DbBuilder.getFirstRowArray(sql);

        if (result.length == 0) {
            return "";
        }
        return result[0].toString();
    }


    public static boolean hasMemberByMx(String strWxID) {

        String table = StringUtils.GetWxTableName(strWxID);
        String sql = String.format("select * from %s where WxID=%s", table, strWxID);

        int length = DbBuilder.getCount(sql);

        if (length == 0) {
            return false;
        }
        return true;
    }


    /**
     * 插入手机好,不考虑并发异常
     * @param strMobile
     * @return
     */
    public static String InsetMemberByMobile(String strMobile) {

        if(hasMemberByMobile(strMobile))
        {
            return  getMemberByMobile(strMobile);
        }

        String table = StringUtils.GetMobileTableName(strMobile);

        String sql = " insert into " + table + " (MEMB_MOBILE,MEMB_ID) values(?,?)";

        String strNewID = GetNewMemberID();

        Object[] params = {strMobile, strNewID};

        DbBuilder.save(sql, params);

        return strNewID;

    }
}